import { Controller } from 'egg';
import * as path from 'path';
import sendToWormhole from 'stream-wormhole';
import { createWriteStream } from 'fs';
import * as reSize from 'resize-img';
import * as fs from 'fs';

class UploadController extends Controller {
  /**
   * 上传图片
   */
  public async upload() {
    const { ctx } = this;
    const stream = await this.ctx.getFileStream();
    if (stream.filename) {
      const basename = path.basename(stream.filename).split('.');
      const len = basename.length - 1;
      const imgUrl = basename[len]; // 文件后缀
      const newName = this.ctx.helper.genImgName() + '.';
      const newUrl = newName + imgUrl;
      const localFilePath = path.join(__dirname, "../public/img", newUrl); //本地文件相对位置
      try {
        stream.pipe(createWriteStream(localFilePath));
        let result: any = await new Promise((resolve) => {
          stream.on('end', function () {
            reSize(fs.readFileSync(localFilePath), { width: 200 }).then(buf => {
              const imgName = ctx.helper.genUUID() + '.' + imgUrl;
              const newUrl = path.join(__dirname, '../public/img/', imgName);
              fs.writeFileSync(newUrl, buf);
              resolve({ code: 1, msg: '上传图片成功', data: { url: imgName } });
            }).catch(e => {
              resolve({ code: 2, msg: '上传失败,请重新上传' + e });
            })
          })
        })
        if (result.code === 1) {
          const returnData = { imgName: result.data.url };
          fs.unlinkSync(localFilePath);
          ctx.body = ctx.helper.responseSuccess('上传成功', returnData);
        } else {
          fs.unlinkSync(localFilePath);
          ctx.body = ctx.helper.responseErrorMsg('上传失败' + result.msg);
        }
      } catch (e) {
        ctx.body = ctx.helper.responseErrorMsg('上传失败' + e.message);
      }
    } else {
      await sendToWormhole(stream);
      ctx.body = ctx.helper.responseErrorParam('请上传文件');
    }
  }

  /**
   * 导出excel职员表
   */
  public async exportEmployeeExcel() {
    const { ctx, ctx: { query } } = this;
    const result: any = await ctx.service.uploadService.exportEmployeeExcel(query);
    ctx.attachment(result.name);
    ctx.body = result.data;
  }

  /**
   * 导出excel打分表
   */
  public async exportGradeList() {
    const { ctx, ctx: { query } } = this;
    try {
      ctx.validate({
        project_id: 'string'
      }, query)
    } catch (e) {
      ctx.body = ctx.helper.responseErrorParam(e.errors[0].message);
      return;
    }
    const result: any = await ctx.service.uploadService.exportGradeList(query);
    ctx.attachment(result.name);
    ctx.body = result.data;
  }
}
export default UploadController;